package shanghaielectric.com.shanghaielectric.RDBHelper;

import android.util.Log;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import shanghaielectric.com.shanghaielectric.DBConfig.DB.DBHelper_config;
import shanghaielectric.com.shanghaielectric.DeviceConfigModel.Point.PointEnumData;
import shanghaielectric.com.shanghaielectric.EnumDataHelper;
import shanghaielectric.com.shanghaielectric.DeviceConfigModel.Device.Device;
import shanghaielectric.com.shanghaielectric.DeviceConfigModel.Point.Point;
import shanghaielectric.com.shanghaielectric.MyEventBus.MyEventBusModel;
import shanghaielectric.com.shanghaielectric.RDBHelper.DataPushHelper.ObserverManager;
import shanghaielectric.com.shanghaielectric.Utils.ByteUtils;
import shanghaielectric.com.shanghaielectric.Utils.DoubleUtils;
import shanghaielectric.com.shanghaielectric.Utils.MyArrayUtils;
import shanghaielectric.com.shanghaielectric.Utils.MySystemUtil;

/**
 * Created by cuihanbing on 2017/10/31.
 */

public class RDBHelper {
    private static RDBHelper rdbHelper;
    private Map<Integer, Device> deviceMap = new LinkedHashMap<>();
    private List<PointEnumData> pointEnumDataList = new ArrayList<>();

    /**
     * cellsCollection,存储了所有通信过来的数据Cell集合
     */
    private Map<Integer, Map<Integer, Cell>> cellsCollection = new LinkedHashMap<>();
    /**
     * cellsCollection_show,存储了所有对外推送数据Cell_show集合
     */
    private Map<Integer, Map<Integer, Cell_show>> cellsCollection_show = new LinkedHashMap<>();

    public Map<Integer, Map<Integer, Cell>> getCellsCollection() {
        return cellsCollection;
    }

    public Map<Integer, Cell> getCellsCollection(int deviceID) {
        return cellsCollection.get(deviceID);
    }

    public Map<Integer, Map<Integer, Cell_show>> getCellsCollection_show() {
        return cellsCollection_show;
    }

    public static RDBHelper getInstance() {
        if (rdbHelper == null) {
            rdbHelper = new RDBHelper();
            Log.e("rebHelper", "new ++++++++");
            return rdbHelper;
        } else {
            return rdbHelper;
        }
    }

    private RDBHelper() {
        deviceMap = DBHelper_config.getDBHelper_config().getDevices();
        pointEnumDataList = DBHelper_config.getDBHelper_config().getPointEnumDataList();

        List<Integer> deviceIDlist = new ArrayList<>();
        for (Map.Entry<Integer, Device> entry : deviceMap.entrySet()) {
            deviceIDlist.add(entry.getKey());
        }
//初始化点集合
        for (int i = 0; i < deviceMap.size(); i++) {
            Map<Integer, Cell> cell_inMap = new LinkedHashMap<>();
            Map<Integer, Cell_show> cell_showMap = new LinkedHashMap<>();

            for (int j = 0; j < deviceMap.get(i + 1).pointList.size(); j++) {
                cell_inMap.put(deviceMap.get(i + 1).pointList.get(j).pointID, new Cell());
                if (deviceMap.get(i + 1).pointList.get(j).isRead) {// cell_show only record the point of read
                    cell_showMap.put(deviceMap.get(i + 1).pointList.get(j).pointID, new Cell_show());
                }
            }
            cellsCollection.put(deviceIDlist.get(i), cell_inMap);
            cellsCollection_show.put(deviceIDlist.get(i), cell_showMap);
//            Map<Integer, Cell_write_basic> cellWriteBasicHashMap = new HashMap<>();
//            cellsCollection_write.put(deviceIDlist.get(i), cellWriteBasicHashMap);
        }
    }

    /**
     * 为推显示点集合添加点值，有则修改，无则添加
     */
    public void putPointValue_commValue(int deviceID, int pointID, int mCommValue) {//mCommValue--
        Device device = deviceMap.get(deviceID);
        //取出点
        Point point = new Point();
        for (int i = 0; i < device.pointList.size(); i++) {
            if (pointID == device.pointList.get(i).pointID) {
                point = device.pointList.get(i);
            }
        }
        Cell cell = new Cell();

//通信值
        cell.commValue = mCommValue;
//读写类型
        cell.readWriteType = point.isRead ? EnumDataHelper.READ_WRITE_TYPE.READ : EnumDataHelper.READ_WRITE_TYPE.WRITE;
//真实值
        Object pointRealValue = null;
        Object mShowValue = 0;
        if (EnumDataHelper.POINT_DATETYPE.ENUM.equals(point.pointDatetype)) {
            for (int i = 0; i < pointEnumDataList.size(); i++) {
                if (pointEnumDataList.get(i).pointID == pointID && pointEnumDataList.get(i).enumKey == mCommValue) {
                    pointRealValue = pointEnumDataList.get(i).enumValue;
                    mShowValue = pointRealValue;
                }
            }
        } else if (EnumDataHelper.POINT_DATETYPE.DOUBLE.equals(point.pointDatetype)) {
//double
            pointRealValue = mCommValue * point.scale;
            mShowValue = DoubleUtils.formatDoubleData(mCommValue * point.scale, point.precision);

        } else if (EnumDataHelper.POINT_DATETYPE.INT.equals(point.pointDatetype)) {
//int
            pointRealValue = mCommValue * point.scale;
            mShowValue = (int) DoubleUtils.formatDoubleData(mCommValue * point.scale, point.precision);
        } else if (EnumDataHelper.POINT_DATETYPE.ENUM_BIT.equals(point.pointDatetype)) {
//BIT
            mShowValue=MyArrayUtils.byteArrayToHexStr( ByteUtils.shortToByte2((short)mCommValue));



//            for (int i = 0; i < pointEnumDataList.size(); i++) {
//                //save enum struct of this point
//                Map<Integer, String> enumValues = new LinkedHashMap<>();
//                List<String> infolist = new ArrayList<>();
//                if (pointEnumDataList.get(i).pointID == pointID) {
//                    enumValues.put(pointEnumDataList.get(i).enumKey, pointEnumDataList.get(i).enumValue);
//
//                    pointRealValue = pointEnumDataList.get(i).enumValue;
//                    mShowValue = pointRealValue;
//                }
//            }
        }

        cell.realValue = pointRealValue;
//显示值
        cell.showValue = String.valueOf(mShowValue);
//单位
        cell.unit = point.unit;
//是否已经推送标志位
        cell.isNew = false;
        Map<Integer, Cell> cell_inMap = cellsCollection.get(deviceID);
        cell_inMap.put(pointID, cell);
        cellsCollection.put(deviceID, cell_inMap);
/**
 *初始化 推送显示点
 * */
        if (cell.readWriteType.equals(EnumDataHelper.READ_WRITE_TYPE.READ)) {
            Map<Integer, Cell_show> cell_showMap = cellsCollection_show.get(deviceID);
            Cell_show cell_show = new Cell_show();
            cell_show.deviceID = deviceID;
            cell_show.pointID = pointID;
            cell_show.showValue = cell.showValue;
            cell_show.unit = cell.unit;
            cell_showMap.put(pointID, cell_show);
            cellsCollection_show.put(deviceID, cell_showMap);
            Log.e("showvalue---", "" + cell_showMap.get(pointID).showValue);
        }


//        ObserverManager.getInstance().notifyObserver_UI(cellsCollection_show);


        Log.e("showvalue", "" + cellsCollection_show.get(deviceID).get(pointID).showValue);
    }

    /**
     * 为下发数据点集合添加点值，有则修改，无则添加
     */

    public void putPointValue_writeValue(int deviceID, int pointID, String putWriteValue) {//输入原始值（string/double...）
        Device device = deviceMap.get(deviceID);
        //取出点
        Point point = new Point();
        for (int i = 0; i < device.pointList.size(); i++) {
            if (pointID == device.pointList.get(i).pointID) {
                point = device.pointList.get(i);
            }
        }
        Cell cell = new Cell();
        int realValue_write = 0;
        try {
            if (EnumDataHelper.POINT_DATETYPE.ENUM.equals(point.pointDatetype)) {
                for (int i = 0; i < pointEnumDataList.size(); i++) {
                    if (pointEnumDataList.get(i).pointID == pointID && pointEnumDataList.get(i).enumValue.equals(putWriteValue)) {
                        realValue_write = pointEnumDataList.get(i).enumKey;
                    }
                }
            } else if (EnumDataHelper.POINT_DATETYPE.INT.equals(point.pointDatetype)) {
                realValue_write = (int) DoubleUtils.formatDoubleData((Double.valueOf(putWriteValue) / point.scale), point.precision);

            } else if (EnumDataHelper.POINT_DATETYPE.DOUBLE.equals(point.pointDatetype)) {
                realValue_write = (int) DoubleUtils.formatDoubleData((Double.valueOf(putWriteValue) / point.scale), point.precision);

            } else if (EnumDataHelper.POINT_DATETYPE.BOOL.equals(point.pointDatetype)) {
//开关量

            } else if (EnumDataHelper.POINT_DATETYPE.TIME.equals(point.pointDatetype)) {
//时间量
            }
        } catch (Exception e) {
            MyEventBusModel myEventBusModel = new MyEventBusModel();
            myEventBusModel.tag = "Exception";
            myEventBusModel.exceptionObj = MySystemUtil.getMethonNmae(RDBHelper.class) + ":" + e.toString() + "";
            EventBus.getDefault().post(myEventBusModel);
        }
        cell.commValue = realValue_write;
        cell.isNew = true;
        cell.readWriteType = EnumDataHelper.READ_WRITE_TYPE.WRITE;
        Map<Integer, Cell> cellMap = cellsCollection.get(deviceID);
        if (cellsCollection.get(deviceID).size() == 0) {//该点数据不存在
            cellMap.put(pointID, cell);
        } else if (cellsCollection.get(deviceID).containsKey(pointID)) {//已存在，更新
////            cellMap.replace(pointID, cell);
//            cellMap.remove(pointID);
            cellMap.put(pointID, cell);
        }
//        cellsCollection.replace(deviceTypeID, cellMap);
//        cellsCollection.remove(deviceTypeID);
        cellsCollection.put(deviceID, cellMap);
        /**
         * 通知通信模块，下发数据
         */
        ObserverManager.getInstance().notifyObserver_Write(cellsCollection);
    }
}
